package cn.bugstack.springframework.core.io;

import cn.hutool.core.lang.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @param
 * @author oyz
 * @version 1.0
 * @description: TODO 通过url的方法来读取文件的信息
 * @date 2022/3/20 15:10
 */
public class UrlResource implements Resource {

    private final URL Url;

    public UrlResource(URL url) {
        Assert.isNull(url,"URL must not be null");
        this.Url = url;
    }


    @Override
    public InputStream getInputStream() throws IOException {
        URLConnection connection = this.Url.openConnection();
        try {

            return connection.getInputStream();
        }catch (IOException e){
            if(connection instanceof HttpURLConnection){
                ((HttpURLConnection) connection).disconnect();
            }
            throw  e;
        }
    }
}
